/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 * Description: remote ipc rma buffer implement
 */

#include "remote_ipc_rma_buffer_impl.h"
#include "adapter_rts.h"
#include "sal.h"
#include "device_capacity.h"
#include "hccl_network.h"

namespace hccl {
RemoteIpcRmaBufferImpl::RemoteIpcRmaBufferImpl(const HcclNetDevCtx netDevCtx)
    : RmaBuffer(nullptr, 0, HcclMemType::HCCL_MEM_TYPE_NUM, RmaType::IPC_RMA), netDevCtx(netDevCtx)
{
}

RemoteIpcRmaBufferImpl::~RemoteIpcRmaBufferImpl()
{
}

HcclResult RemoteIpcRmaBufferImpl::Deserialize(const std::string& msg)
{
    std::istringstream iss(msg);
    iss.read(reinterpret_cast<char_t *>(&memName.ipcName), sizeof(memName.ipcName));
    iss.read(reinterpret_cast<char_t *>(&memOffset), sizeof(memOffset));
    HCCL_DEBUG("[RemoteIpcRmaBufferImpl][Deserialize]ipcName[%s], memOffset[%lu]", memName.ipcName, memOffset);
    return HCCL_SUCCESS;
}

HcclResult RemoteIpcRmaBufferImpl::Open()
{
    if (memType == HcclMemType::HCCL_MEM_TYPE_HOST) {
        HCCL_ERROR("[RemoteIpcRmaBufferImpl][Open]remote memType[%d] not support.", memType);
        return HCCL_E_PARA;
    }

    CHK_PTR_NULL(netDevCtx);
    s32 deviceLogicId = (static_cast<NetDevContext *>(netDevCtx))->GetLogicId();
    bool firstOpened = false;
    HcclResult ret = MemNameRepository::GetInstance(deviceLogicId)
        ->OpenIpcMem(&devAddr, size, memName.ipcName, HCCL_IPC_MEM_NAME_LEN, memOffset, firstOpened);
    CHK_PRT_RET(ret != HCCL_SUCCESS,
        HCCL_ERROR("[RemoteIpcRmaBufferImpl][Open]errNo[0x%016llx] Open ipc mem failed. memName[%s], offset[%llu]",
            HCCL_ERROR_CODE(ret), memName.ipcName, memOffset), ret);
    return HCCL_SUCCESS;
}

HcclResult RemoteIpcRmaBufferImpl::Close()
{
    CHK_PTR_NULL(netDevCtx);
    s32 deviceLogicId = (static_cast<NetDevContext *>(netDevCtx))->GetLogicId();
    MemNameRepository::GetInstance(deviceLogicId)
        ->CloseIpcMem(static_cast<const u8 *>(memName.ipcName));
    HCCL_DEBUG("[RemoteIpcRmaBufferImpl][Close]memName[%s]", memName.ipcName);
    return HCCL_SUCCESS;
}
}